<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">欢迎登录</h2>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <div class="register-container">
            <el-button type="info" size="small" plain @click="$router.push('/register')">注册</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const store = useStore()
    const loginFormRef = ref(null)
    const loading = ref(false)

    const loginForm = reactive({
      username: '',
      password: ''
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }

    const handleLogin = async () => {
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const res = await request.post('/auth/login', {
              username: loginForm.username,
              password: loginForm.password,
              isAdmin: 1  // 管理端固定为1
            })
            if (res.code === 200) {
              if (!res.data) {
                // token为null表示无权限
                ElMessage.warning('当前用户无管理员权限')
                return
              }
              
              const token = res.data
              localStorage.setItem('token', token)
              
              const userInfoRes = await request.get('/auth/userinfo', {
                headers: {
                  'Authorization': `Bearer ${token}`
                }
              })
              if (userInfoRes.code === 200) {
                store.commit('setUser', userInfoRes.data)
                ElMessage.success('登录成功')
                router.push('/admin')
              }
            }
          } catch (error) {
            console.error('Login failed:', error)
            const errorMsg = error.response?.data?.message || '登录失败'
            ElMessage.error(errorMsg)
          } finally {
            loading.value = false
          }
        }
      })
    }

    return {
      loginForm,
      loginFormRef,
      rules,
      loading,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('../resources/dlbj.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-card {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.9); /* 添加半透明背景 */
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-title {
  text-align: center;
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.el-button {
  width: 100%;
  margin-bottom: 10px;
}

.register-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.register-container .el-button {
  width: fit-content;  /* 按钮宽度适应文字内容 */
  padding: 8px 20px;   /* 调整内边距 */
  font-size: 14px;
}

/* 移除之前的 el-button 100% 宽度样式 */
.el-form-item .el-button--primary {
  width: 100%;
  margin-bottom: 0;  /* 移除底部间距 */
}
</style> 